package com.oolee.cloud.service;


import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@DefaultProperties(defaultFallback = "globalFallback")
public class PaymentService {


    public String requestHealth(long id){
        return "请求线程: "+Thread.currentThread().getName()+"  请求健康! 当前id: "+id;
    }

    /**
     * 服务降级
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "timeoutFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")
    })
    public String requestUnHealth(long id){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "请求线程: "+Thread.currentThread().getName()+"  请求超时~ 当前id: "+id;
    }


    /**
     * 服务降级被调用方法
     * 注意：此方法参数需和服务降级调用方参数相匹配
     * @return
     */
    public String timeoutFallback(long id){
        return "服务降级 --> 太慢了 ~~~ o(╥﹏╥)o";
    }

    /**
     * 全局默认fallback方法
     * @return
     */
    public String globalFallback(){
        return "全局默认fallback提示您: --> 太慢了 o(╥﹏╥)o";
    }


    /**
     * 熔断器
     * @param id
     * @return
     * 开启熔断器
     * 请求次数     --> 在窗口期请求次数
     * 窗口期      -->  以窗口期计算服务熔断的标准
     * 错误率      -->  在窗口期内错误率达到自定义的概率则服务熔断
     */
    @HystrixCommand(fallbackMethod = "circuitBreakerFallBack",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    public String paymentCircuitBreaker(long id){
        if (id<0){
            throw new RuntimeException("id 不能为负数");
        }
        String serialNum = IdUtil.simpleUUID();
        return "调用成功，此流水号为："+serialNum;
    }

    public String circuitBreakerFallBack(long id){
        return "id 不能为负数，请稍后重试o(╥﹏╥)o";
    }


}
